import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:fixnum/fixnum.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:image_picker/image_picker.dart';
import '../../chat_core/network/connection/connect_util.dart';
import '../../chat_core/network/connection/msg_manager.dart';
import '../../chat_core/network/connection/socket_manager.dart';
import '../../chat_core/pkt/pb.pb.dart';
import '../../chat_model/chatFaqModel.dart';
import '../List_component/ListComponentPage.dart';
import '../utils/util.dart';

class KeyBoardComponentPage extends StatefulWidget {
// 用户信息
  PlayerInfo? playerInfo;

  // 客服信息
  ServicerInfoFields? servicerInfoFields;

  // 消息源
  ChatFields? chatFields;

  // 图片地址
  List<String>? photo;

  // 客户结束对话消息
  EnterStatus? enterStatus;

  // 上传文件状态集合
  Map<String, File>? images;

  //是否禁言理由
  FreezePlayer? freezePlayer;

  //是否已经链接 默认否
  // bool isConnect;

  //faqModel
  FaqModel? faqModel;

  //聊天内容
  List<dynamic>? list;

  bool isVoice = false;

  bool isHideRecord = false;

  String? sessionId;
  String? avater;
  String? name;
  String? content;
  String? userId;
  String? appId;

  // 本地图片加载遮罩层
  Map<String, bool> loadingState = {};

  var text;
  Timer? _throttlingTimer;
  GlobalKey<ListComponentPageState> listComponentPageState;

  KeyBoardComponentPage({
    super.key,
    required this.listComponentPageState,
    this.appId,
    this.playerInfo,
    this.servicerInfoFields,
    this.chatFields,
    this.enterStatus,
    this.images,
    this.freezePlayer,
    this.faqModel,
    this.list,
    this.content,
    this.userId,
    this.text,
  });

  @override
  State<KeyBoardComponentPage> createState() => KeyBoardComponentPageState();
}

class KeyBoardComponentPageState extends State<KeyBoardComponentPage> {
  TextEditingController? editController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    editController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    editController!.text = widget.text ?? "";
    var textField = TextField(
      keyboardType: TextInputType.text,
      cursorColor: Colors.blue,
      controller: editController,
      maxLines: 100,
      minLines: 1,
      enabled: widget.freezePlayer?.type == 1 ? false : true,
      decoration: InputDecoration(
        hintText: widget.freezePlayer?.type == 1 ? "您已被禁言" : "输入文字",
        filled: true,
        fillColor: Colors.white,
        contentPadding:
            const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        isDense: true,
        border: const OutlineInputBorder(
          gapPadding: 0,
          borderRadius: BorderRadius.all(Radius.circular(46)),
          borderSide: BorderSide(
              width: 1,
              // style: BorderStyle.none,
            color: Color(0xffe6e6e6),),
        ),
        enabledBorder: const OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(46)),
          borderSide: BorderSide(
            color: Color(0xffe6e6e6),
            width: 0.5,
            // style: BorderStyle.none,
          ),
        ),
        focusedBorder: const OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(46)),
          borderSide: BorderSide(
            color: Color(0xffe6e6e6),
            width: 1,
            // style: BorderStyle.none,
          ),
        ),
      ),
      onChanged: (v) {
        widget.text = v;
        // 节流处理
        widget._throttlingTimer?.cancel();
        widget._throttlingTimer = null;
        widget._throttlingTimer =
            Timer(const Duration(milliseconds: 300), () => onStartInput());
      },
    );

    var voice = GestureDetector(
      onPanDown: (s) {
        print('开始');
        // dispatch(KeyBoardActionCreator.onRecordVoice());
      },
      onPanCancel: () {
        print('结束');
        // dispatch(KeyBoardActionCreator.onStopRecord());
        // dispatch(ChatActionCreator.cancelRecordUI());
      },
      onVerticalDragEnd: (v) {
        // dispatch(KeyBoardActionCreator.onStopRecord());
        // dispatch(ChatActionCreator.cancelRecordUI());
      },
      child: Container(
        height: 32,
        decoration: BoxDecoration(
            border: Border.all(color: Colors.grey.withOpacity(0.4), width: 0.5),
            borderRadius: const BorderRadius.all(Radius.circular(10))),
        child: const Center(
          child: Text('按住讲话'),
        ),
      ),
    );
    // 消息内容
    return SafeArea(
        child: Column(
      children: <Widget>[
        // const Divider(
        //   height: 0.5,
        //   color: Colors.grey,
        //   endIndent: 0,
        //   indent: 0,
        // ),
        Container(
          height: 68,
          width: double.infinity,
          color: Colors.white,
          child: Row(
            children: <Widget>[
              12.horizontalSpace,
              SocketManager().model?.isVoice == false
                  ? GestureDetector(
                      onTap: () {
                        FocusScope.of(context).requestFocus(FocusNode());
                        if (widget.freezePlayer?.type != 1) {
                          if (widget.isVoice == true) {
                            widget.isVoice = false;
                          } else {
                            widget.isVoice = true;
                          }
                          setState(() {});
                        }
                      },
                      child: Container(
                          height: 24,
                          width: 24,
                          margin: const EdgeInsets.only(
                              top: 10, bottom: 10, left: 0, right: 10),
                          child: SvgPicture.asset(
                            widget.isVoice == false
                                ? "assets/svg/video_play.svg"
                                : "assets/svg/video_play.svg",
                            color: SocketManager().model?.primaryColor,
                          )))
                  : Container(),
              Expanded(child: widget.isVoice == true ? voice : textField),
              Container(
                margin: const EdgeInsets.only(left: 10),
                child: GestureDetector(
                  onTap: () {
                    if (widget.freezePlayer?.type == 1 ||
                        Instance.isConnect == false) {
                    } else {
                      _showModalBottomSheet(widget.appId!);
                    }
                  },
                  child: Container(
                      padding:
                          const EdgeInsets.only(right: 10, top: 10, bottom: 10),
                      child: SizedBox(
                        height: 24,
                        width: 24,
                        child: Image.asset(
                          "assets/images/shop/msg_img_ic.png",
                          color: SocketManager().model?.primaryColor,
                        ),
                      )
                      // child: Image.asset('assets/images/msg.png',
                      //         package: 'chat_online_customers',
                      //         color: ChatColor.selectPicColor),
                      ),
                ),
              ),
              GestureDetector(
                onTap: () {
                  if (widget.freezePlayer?.type == 1) {
                  } else {
                    if (widget.text != null && widget.text.length > 0) {
                      Map<String, dynamic> textMap = Map();
                      textMap["text"] = widget.text;
                      onSendMsg(textMap);

                      //重置是否滚动到底部状态
                      widget.listComponentPageState.currentState
                          ?.onChangeIsScrollToBottom(true);
                      editController!.text = '';
                      widget.text = '';
                      setState(() {});
                    } else {
                      print('请输入消息内容');
                    }
                  }
                },
                child: Container(
                    padding:
                        const EdgeInsets.only(top: 10, bottom: 10, right: 12),
                    child: Image.asset(
                      "assets/images/hj_mine/msg_send_ic.png",
                      width: 32,
                      height: 32,
                    )),
              ),
            ],
          ),
        )
      ],
    ));
  }

  _showModalBottomSheet(String widgetAppId) {
    final List<String> textList = ['相册', '拍照', '取消'];
    showModalBottomSheet(
        isScrollControlled: true,
        context: context,
        builder: (context) => SafeArea(
              child: SizedBox(
                height: 180,
                child: ListView(
                    children: List.generate(
                  textList.length,
                  (index) => InkWell(
                      child: Container(
                          alignment: Alignment.center,
                          height: 60.0,
                          child: Text(textList[index])),
                      onTap: () {
                        if (index == 0) {
                          getImageByGallery(widgetAppId);
                        } else if (index == 1) {
                          getImageByCamera(widgetAppId);
                        } else if (index == 2) {}
                        Navigator.pop(context);
                      }),
                )),
              ),
            ));
  }

  Future getImageByGallery(String widgetAppId) async {
    var image = await ImagePicker().pickImage(source: ImageSource.gallery);
    var tw = 400;
    XFile? _image = image;
    ImageProperties properties =
        await FlutterNativeImage.getImageProperties(_image!.path);
    File compressedFile = await FlutterNativeImage.compressImage(_image.path,
        quality: 80,
        // percentage: 100,
        targetWidth: tw,
        targetHeight: (properties.height! * tw / (properties.width!)).round());
    //重置是否滚动到底部状态
    widget.listComponentPageState.currentState?.onChangeIsScrollToBottom(true);
    //拍照获取图片上传
    onUpPic(compressedFile, widgetAppId);
  }

//图片上传
  void onUpPic(File compressedFile, String widgetAppId) async {
    String path = compressedFile.path;
    List<int> imageBytes = await compressedFile.readAsBytes();
    var name = widgetAppId + DateTime.now().millisecondsSinceEpoch.toString();
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(
        path,
        filename: name,
      )
    });
    Dio dio = Dio();
    dio.options.headers[HttpHeaders.contentTypeHeader] =
        "application/json, multipart/form-data";
    var userId = await obtainValueByKey('id') ?? '';
    var appId = widgetAppId ?? '';
    var sessionId = await obtainValueByKey('sessionId') ?? '';
    dio.options.headers["Authorization"] = "$userId&$appId&$sessionId";
    print(dio.options.headers);
    //"${Api.baseUrl}/file/$name";
    String uri =
        "${SocketManager().model?.baseUrl}/kefu/file/$name"; //"http://183.61.126.215:9090/file/$name";

    Map<String, dynamic> map = {};
    map['base64'] = base64Encode(imageBytes);
    var username = await obtainValueByKey('username') ?? '';
    //拼接本地图片 直接展示到列表-------下
    int time = DateTime.now().millisecondsSinceEpoch;
    ChatFields chatFields = ChatFields.create()
      ..type = 1
      ..username = username.toString()
      ..time = Int64(time);
    chatFields.photo.add("$name^${map['base64']}");

    widget.listComponentPageState.currentState
        ?.onIsShowLoading({'$name': true});
    widget.listComponentPageState.currentState?.onShowChatFields(chatFields);
    // //拼接本地图片 直接展示到列表-------上
    try {
      var response = await dio.post(uri, data: formData,
          onSendProgress: (int sent, int total) {
        // double t = sent / total;
      });
      if (response.data["data"] != null) {
        map["pic"] = response.data["data"];
        onSendMsg(map);
      } else {
        print("图片上传失败");
      }
    } catch (e) {
      Map<String, File> file = {};
      file[Int64(time).toString()] = compressedFile;
      widget.listComponentPageState.currentState?.onUpPicError(file);
      throw UnimplementedError(e.toString());
    } finally {
      widget.listComponentPageState.currentState?.onIsShowLoading({name: true});
      widget.listComponentPageState.currentState
          ?.onChangeIsScrollToBottom(true);
    }
  }

  //文本消息内容
  void onSendMsg(Map<String, dynamic> map) async {
    widget.listComponentPageState.currentState?.onChangeIsScrollToBottom(true);
    int nowTime = DateTime.now().millisecondsSinceEpoch;
    // dynamic data = ctx.state.list;
    //判断当前webSocket是否是链接状态 是连接状态就直接聊天  没有链接 如果用户点击消息发送 就显示faq
    if (Instance.isConnect == true) {
      ChatFields chatFields = ChatFields.create()
        ..sessionId = await obtainValueByKey('sessionId').toString()
        ..text = map["text"].toString().isNotEmpty ? map["text"].toString() : ""
        ..time = Int64(nowTime)
        ..username = await obtainValueByKey('username').toString()
        ..targetId = await obtainValueByKey('servicerId').toString()
        ..type = 1
        ..senderId = await obtainValueByKey('id').toString()
        ..messageId = nowTime.toString();

      if (map['pic'] != null) {
        chatFields.photo.add("${map["pic"]}");
      }
      BaseMessage baseMessage = BaseMessage.create();
      baseMessage.action = 1003;
      baseMessage.data = chatFields.writeToBuffer();
      MsgUtils.sendMessage(baseMessage.writeToBuffer());
      if (map['pic'] == null) {
        widget.listComponentPageState.currentState
            ?.onShowChatFields(chatFields);
        widget.listComponentPageState.currentState?.onShow(chatFields);
      } else {
        if (widget.faqModel != null) {
          ServicerInfoFields servicerInfoFields = ServicerInfoFields.create();
          servicerInfoFields.declaration = '客服妹子正在忙哦～请先查看相关常见问题';
          widget.listComponentPageState.currentState
              ?.onShowChatFields(servicerInfoFields);
          //展示faq问题组件
          Future.delayed(const Duration(seconds: 1), () {
            widget.listComponentPageState.currentState
                ?.onShowChatFields(widget.faqModel);
          });
        }
      }
    }
  }

  Future getImageByCamera(String widgetAppId) async {
    var image = await ImagePicker().pickImage(source: ImageSource.camera);
    XFile? _image = image;
    var tw = 400;
    ImageProperties properties =
        await FlutterNativeImage.getImageProperties(_image!.path);
    File compressedFile = await FlutterNativeImage.compressImage(_image.path,
        quality: 80,
        targetWidth: tw,
        targetHeight: (properties.height! * tw / properties.width!).round());
    //重置是否滚动到底部状态
    widget.listComponentPageState.currentState?.onChangeIsScrollToBottom(true);
    //拍照获取图片上传
    onUpPic(compressedFile, widgetAppId);
  }

// 用户开始输入
  void onStartInput() async {
    BaseMessage baseMessage = BaseMessage.create();
    baseMessage.action = 1012;
    baseMessage.data = (EnterStatus.create()
          ..senderId = await obtainValueByKey('id') == null
              ? ""
              : obtainValueByKey('id').toString()
          ..targetId = await obtainValueByKey('servicerId') == null
              ? ""
              : obtainValueByKey('servicerId').toString())
        .writeToBuffer();
    MsgUtils.sendMessage(baseMessage.writeToBuffer());
  }

  void onDontTalk(FreezePlayer freezePlayer) {
    onShutUp(freezePlayer);
    if (freezePlayer.type == 1) {
      //禁言
      ServicerInfoFields servicerInfoFields = ServicerInfoFields.create();
      servicerInfoFields.declaration = freezePlayer.reason ?? "你已被禁言";
      widget.listComponentPageState.currentState
          ?.onShowChatFields(servicerInfoFields);
    } else if (freezePlayer.type == 2) {
      //解除
      ServicerInfoFields servicerInfoFields = ServicerInfoFields.create();
      servicerInfoFields.declaration = freezePlayer.reason ?? "您已解除禁言";
      widget.listComponentPageState.currentState
          ?.onShowChatFields(servicerInfoFields);
    }
  }

  void onShutUp(FreezePlayer freezePlayer1) {
    widget.freezePlayer = freezePlayer1;
    setState(() {});
  }

  void onEnterStatus(EnterStatus enterStatus) {
    widget.enterStatus = enterStatus;
    setState(() {});
  }
}
